package com.jfl.service.impl.system;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Service;
import com.google.common.collect.Maps;
import com.jfl.base.BaseServiceImpl;
import com.jfl.mapper.SysSessionMapper;
import com.jfl.model.SysSession;
import com.jfl.system.SysSessionService;
import com.jfl.utils.DateUtil;

/**
 * 会话Service
 * 
 * @author 赵炎
 * @version [V1.00, 2018年12月5日]
 * @since V1.00
 */
@Component
@Service(version="${jfl.version}")
public class SysSessionServiceImpl extends BaseServiceImpl<SysSession, SysSessionMapper> implements SysSessionService
{
    /**
     * 过期时间 单位s
     */
    @Value("${jfl.session.expire}")
    private long expire;
    
    /**
     * 重写方法
     * @param userName
     * @return
     * @see com.jfl.system.SysSessionService#querySessionByUserName(java.lang.String)
     */
    @Override
    public List<SysSession> querySessionByUserName(String userName)
    {
        Map<String,Object> colmnMap = Maps.newHashMap();
        colmnMap.put("user_name", userName);
        return this.mapper.selectByMap(colmnMap);
    }

    /**
     * 重写方法
     * @param sessionId
     * @see com.jfl.system.SysSessionService#deleteBySessionId(java.lang.String)
     */
    @Transactional
    @Override
    public void deleteBySessionId(String sessionId)
    {
        this.mapper.deleteBySessionId(sessionId);
    }
    
    @Override
    public void deleteExpireSession()
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("==> 删除过期缓存开始");
        }
        // 当前系统时间
        Date current = DateUtil.getCurrentDate();
        // 获取全部session会话
        List<SysSession> sessions = this.mapper.selectByMap(Maps.newHashMap());
        if (sessions != null && !sessions.isEmpty())
        {
            for (SysSession sysSession : sessions)
            {
                // session开始时间 + 过期时间 > 当前时间
                if ((sysSession.getCreateTime().getTime() + expire * 60 * 1000) < current.getTime())
                {
                    try
                    {
                        this.mapper.deleteBySessionId(sysSession.getSessionId());
                    }
                    catch (Exception e)
                    {
                        logger.error("删除session缓存异常", e);
                    }
                }
            }
            
        }
        if (logger.isDebugEnabled())
        {
            logger.debug("==> 删除过期缓存结束");
        }
    }
    
}
